package com.cn.ssm.servlet;

import com.cn.ssm.model.CityInfo;
import com.cn.ssm.model.RoleInfo;
import com.cn.ssm.model.UserRoleInfo;
import com.cn.ssm.permisson.PermissionManager;
import com.cn.ssm.service.*;
import org.springframework.ui.Model;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

public class LoginInterceptor implements HandlerInterceptor {
    @Resource
    PermissionManager permissionManager;

    @Resource
    BureauInfoService bureauInfoService;

    @Resource
    UserInfoService userInfoService;

    @Resource
    UserRoleInfoService userRoleInfoService;

    @Resource
    RoleInfoService roleInfoService;

    @Resource
    CityInfoService cityInfoService;


    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        System.out.println("LoginInterceptor------>preHandle");
        ServletContext servletContext=httpServletRequest.getSession().getServletContext();
        Object seq=httpServletRequest.getParameter("sequencenum");
        String sequencenum=seq==null?"":seq.toString();
        String PermissionCode="";
        String PermissionCode2="";
        List<Map<String,Object>> list=userInfoService.selectBySeques(sequencenum);
        if(list!=null){
            Map<String,Object> mp=  list.get(0);
            HttpSession session=httpServletRequest.getSession();
            servletContext.setAttribute("user",mp);
            String username=mp.get("USERNAME")==null?"":mp.get("USERNAME").toString();
            String bureausequencenum=mp.get("BUREAUSEQUENCENUM")==null?"":mp.get("BUREAUSEQUENCENUM").toString();
            String citysequencenum=mp.get("CITYSEQUENCENUM")==null?"":mp.get("CITYSEQUENCENUM").toString();
            boolean ok=false;

            if("admin".equals(username)){
                session.setAttribute("permission_name0_0_0", username);
                session.setAttribute("permission0", "0_0_0");
                session.setAttribute("permission2_0", username);
                session.setAttribute("permission3_0", "admin");
                session.setAttribute("permission4_0", "all");
                Object ob = servletContext.getAttribute("users");              // 获取当前的用户容器。
                servletContext.setAttribute("users", permissionManager.addUser(ob, session)); // 修改用户容器，并添加到application变量中
            }
            List<CityInfo> cityes=cityInfoService.selectBysequesnum(citysequencenum);
            Object obj = servletContext.getAttribute("users");
            permissionManager.setVector(obj);
            List<Map<String,Object>> roles =userInfoService.selectRoleBySeques(sequencenum);

            /**
             * 判断当前是否存在相同权限的用户
             */
            //获取当前用户所拥有的角色
            for(Map<String,Object> m:roles){
                String role=m.get("ROLECODE")==null?"":m.get("ROLECODE").toString();
                PermissionCode=bureausequencenum+"_"+citysequencenum+"_"+role;
                PermissionCode2+=PermissionCode+":";
                if(!permissionManager.checkPermission(PermissionCode)){
                    session.setAttribute("permission_name"+PermissionCode,username);
                    ok=true;
                }
            }
            //权限重复 跳转到登录页面
            if(!ok){
                httpServletResponse.sendRedirect("/index.jsp");
            }

            //一般用户判定
            session.setAttribute("permission1", PermissionCode2);
            session.setAttribute("permission2_1", username);
            session.setAttribute("permission3_1", getRoleStr(sequencenum));
            session.setAttribute("permission4_1", cityes.get(0).getName());
            Object ob1= servletContext.getAttribute("users");              // 获取当前的用户容器。
            servletContext.setAttribute("users", permissionManager.addUser(ob1, session)); // 修改用户容器，并添加到application变量中
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        System.out.println("LoginInterceptor------>postHandle");
        Map<String, Object>  model=modelAndView.getModel();
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        System.out.println("LoginInterceptor------>afterCompletion");
    }

    //获取角色字符串
    public String getRoleStr(String SequenceNum)
    {
        List<UserRoleInfo> userroleinfos=userRoleInfoService.selectByuserseq(SequenceNum+"");
        String roleStr="";
        for(UserRoleInfo userRoleInfo:userroleinfos){
            String rolecode=userRoleInfo.getRolecode();
            List<RoleInfo> roleinfos=roleInfoService.selectBycode(rolecode);
            for(RoleInfo roleinfo:roleinfos){
                roleStr+=roleinfo.getName()+"/";
            }
            String BureauSequenceNum=userRoleInfo.getBureausequencenum();
            if(BureauSequenceNum=="0")
                roleStr+="全市局"+"；\n";
            else
            {
                List<Map<String,Object>> bur=bureauInfoService.selectBynum(BureauSequenceNum);
                for(Map<String,Object> map:bur){
                    roleStr+=map.get("Name")+"；\n";
                }

            }
        }

        if(roleStr.length()>2)
            roleStr=roleStr.substring(0,roleStr.length()-2)+"。";

        return roleStr;
    }
}
